#include "collision_manager.h"
#include "director.h"

using namespace alice;

CollisionManager* CollisionManager::instance_ = nullptr;

CollisionManager::CollisionManager() {
  collision_layer_ = (TileLayer*)Director::GetInstance()->GetMap()->GetMapLayers().front();
  layer_tile_map_ = collision_layer_->GetTileMap();
}

bool CollisionManager::CheckCollision(SDL_Rect a, SDL_Rect b) {
  bool x_overlaps = (a.x < b.x + b.w) && (a.x + a.w > b.x);
  bool y_overlaps = (a.y < b.y + b.h) && (a.y + a.h > b.y);

  return x_overlaps && y_overlaps;
}

// TODO: 
// 地图碰撞检测在碰到设置于横轴的碰撞体时，
// 会将碰撞体的右侧边框用作有效碰撞区域
// 需要改进，也许可以计算出获取瓦片的面积
// 再使用 CheckCollision 函数进行碰撞检测
bool CollisionManager::MapCollision(SDL_Rect a) {
  int tile_size = 32;
  int row = 20;
  int columns = 60;

  int left_tile = a.x / tile_size;
  int right_tile = (a.x + a.w) / tile_size;
  int top_tile = a.y / tile_size;
  int bottom_tile = (a.y + a.h) / tile_size;

  if (left_tile < 0) left_tile = 0;
  if (right_tile > columns) right_tile = columns;
  if (top_tile < 0) top_tile = 0;
  if (bottom_tile > row) bottom_tile = row;

  for (int i = left_tile; i < right_tile; i++) {
    for (int j = top_tile; j < bottom_tile; j++) {
      if (layer_tile_map_[j][i] > 0) {
        return true;
      }
    }
  }

  return false;
}